<template>
  <div style="height: 60px;background-color: #fff;padding: 10px 20px">
    <span style="line-height: 60px;font-size: 20px">用户管理</span>
    <el-button @click="add_button" type="primary" style="float: right;margin-top: 15px">新建用户</el-button>
  </div>
  <!--新建用户弹窗-->
  <!-- 关闭之前先调用handleClose方法来处理弹窗的关闭问题 -->
  <el-dialog :title="dialog_title"
             style="width: 1000px;padding: 40px"
             v-model="dialog_visible"
             :before-close="handleClose">
    <el-form label-position="top" :rules="save_user_form_rules" :model="save_user_form" ref="formRef">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
<!--      禁用disabled是不会提交表单的      -->
            <el-input v-model="save_user_form.username" placeholder="请输入用户名" :disabled="save_user_form.id"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input  v-model="save_user_form.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职级" prop="level">
                <el-select v-model="save_user_form.level" placeholder="请选择"  @change="load_leader">
                  <el-option v-for="item in level_option" :label="item.username" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="直属领导" prop="parentId">
                <el-select v-model="save_user_form.parentId" placeholder="请选择">
                  <el-option v-for="item in leader_option" :label="item.username" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="save_user_form.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="save_user_form.age" placeholder="请输入年龄"></el-input>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="save_user_form.gender">
                  <el-radio value="1" border style="margin: 0">男</el-radio>
                  <el-radio value="0" border style="margin: 0">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="用户状态" prop="status">
                <el-radio-group v-model="save_user_form.status">
                  <el-radio value="1" border style="margin: 0">启用</el-radio>
                  <el-radio value="0" border style="margin: 0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="save_user" type="primary">保存</el-button>
    </template>
  </el-dialog>
  <!-- 用户搜索卡片 -->
  <el-card :inline="true" style="margin: 20px;height: 70px">
    <el-form :inline="true">
      <el-form-item leable="用户搜索" style="width:220px" ref="">
        <el-input v-model="search_user_form.username" placeholder="请输入用户名" @keydown.enter="load_user"></el-input>
      </el-form-item>
      <el-form-item label="用户状态" style="width:220px">
        <el-select v-model="search_user_form.status" placeholder="请选择用户状态" @change="load_user">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item leable="用户搜索" style="width:220px">
        <el-button @click="reset_search">重置</el-button>
        <el-button @click="load_user" type="primary">查询</el-button>
      </el-form-item>

    </el-form>

  </el-card>
  <!-- 用户表格卡片 -->
  <el-card style="margin: 20px;overflow: auto">
    <el-table :data="user_arr" height="580px">
      <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
      <el-table-column prop="createTime" label="加入时间" align="center"></el-table-column>
      <el-table-column prop="status" label="用户状态" align="center">
        <template #default="scope">
          <el-switch active-value="1" inactive-value="0" v-model="scope.row.status" @change="change_status(scope.row.id,scope.row.status)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" :disabled="scope.row.level==='40'"
                     @click="reset_password(scope.row.id)">密码重置</el-button>
          <el-button link type="primary" :disabled="scope.row.level==='40'"
                     @click="edit_user(scope.row)">编辑</el-button>
          <el-button link type="primary" :disabled="scope.row.level==='40'"
                     @click="delete_user(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

//控制弹窗是否出现
const dialog_visible = ref(false)
//员工职级选项
const level_option = ref([
  {username:'职员',value:'10'},
  {username:'经理',value:'20'},
  {username:'总监',value:'30'},
  {username:'总裁',value:'40'},
])
//领导选项
const leader_option = ref([])
//添加用户表单数据
const save_user_form = ref({
  //id:'',
  username:'',
  //password:'',
  email:'',
  phone:'',
  age:'',
  gender:'',
  //createTime:'',
  //updateTime:'',
  status:'',
  level:'',
  parentId:''
})
//搜索的表单数据
const search_user_form = ref({username:'',status:''})
//用户数组
const user_arr = ref([])
//弹窗标题
const dialog_title = ref('新增用户')

const formRef = ref(null)
/*新增按钮*/
const add_button = ()=>{
  dialog_visible.value=true
  dialog_title.value='新增用户'
}
/*关闭弹窗*/
const handleClose = ()=>{
  if(confirm('您确认要关闭本窗口吗？')){
    //关闭弹窗，并清空双向绑定的表单数据
    dialog_visible.value=false
    save_user_form.value={username:'', email:'', phone:'',
      age:'', gender:'', status:'', level:'', parentId:''}
    }
    leader_option.value=[]
    // 清除表单验证状态，可选链操作符：?. 来确保在 formRef 未定义时不会抛出错误。
    formRef.value?.resetFields();
    formRef.value?.clearValidate();


}
/*添加/修改用户的方法*/
const save_user = ()=>{

    formRef.value.validate((valid)=>{
      if(!valid){
          ElMessage.error('请检查输入信息')
      }else{
          console.log(save_user_form.value)
          //安装查询字符串qs: npm install qs，使用之前需要导入：import qs from "qs"
          //使用qs框架将JS对象转为查询字符串格式name=tom&age=19,后端的@RequestBody需要去掉
          //后端：@RequestBody用于将http请求体里的内容绑定到方法参数上；
          let data = qs.stringify(save_user_form.value)
          axios.post(BASE_URL+'/v1/user/save',data).then((response)=>{
                  if(response.data.code===2000){
                      ElMessage.success('保存成功');
                      //关闭弹窗，并清空双向绑定的表单数据
                      dialog_visible.value=false
                      save_user_form.value={username:'', email:'', phone:'',
                          age:'', gender:'', status:'', level:'', parentId:''}
                      //清空搜索条件
                      search_user_form.value={}
                      //重新加载数据
                      load_user();
                  }else{
                      ElMessage.error(response.data.msg);
                  }
              })
      }
    })
}
/*加载用户数据的方法*/
const load_user = ()=>{
  //let data = qs.stringify(search_user_form.value)
  axios.get(BASE_URL+'/v1/user/select',{params:search_user_form.value})
      .then((response)=>{
        if(response.data.code===2000){
          user_arr.value = response.data.data;
          console.log(user_arr.value);
        }else{
          ElMessage.error(response.data.msg)
        }
      })
}
/*加载领导的方法*/
const load_leader = ()=>{
  leader_option.value=[]
  save_user_form.value.parentId=''
  let level = parseInt(save_user_form.value.level)+10;
  console.log(level)
  //level拼接后变为字符串
  axios.get(BASE_URL+'/v1/user/select?level='+level)
      .then((response)=>{
        if(response.data.code===2000){
          leader_option.value=response.data.data;
        }else{
          ElMessage.error(response.data.msg)
        }

      })
}
/*重置搜索条件的方法*/
const reset_search = ()=>{
  //清空搜索条件
  search_user_form.value={}
  //重新加载数据
  load_user();
}
/*重置密码*/
const reset_password = (id)=>{
  //restful风格
  axios.post(BASE_URL+'/v1/user/update/password/'+id)
      .then((response)=>{
        if(response.data.code===2000){
          ElMessage.success('修改成功')
        }else{
          ElMessage.error(response.data.msg)
        }
      })
}
/*编辑用户按钮*//*不能直接修改上级领导*/
const edit_user = (row)=>{
  dialog_visible.value=true
  dialog_title.value='编辑用户'
  //回显数据
  save_user_form.value = row
  //显示上级领导名字
  /*axios.get(BASE_URL+'/v1/user/select?id='+row.parentId)
      .then((response)=>{
        if(response.data.code===2000){
          leader_option.value=response.data.data;
        }else{
          ElMessage.error(response.data.msg)
        }
      })*/
  let leader_level = parseInt(row.level)+10

  //显示可选上级领导选项
  axios.get(BASE_URL+'/v1/user/select?level='+leader_level)
      .then((response)=>{
        if(response.data.code===2000){
          leader_option.value=response.data.data;
        }else{
          ElMessage.error(response.data.msg)
        }
      })

}
/*修改状态*/
const change_status = (id,status)=>{
  if(confirm('确认修改吗？')){
    //restful风格(/不能少，否则报错： Failed to execute ‘open‘ on ‘XMLHttpRequest‘: Invalid URL)
    axios.post(BASE_URL+'/v1/user/update/status/'+id+'/'+status)
        .then((response)=>{
          if(response.data.code){
            ElMessage.success('状态修改成功')
          }else{
            ElMessage.error(response.data.msg)
          }
        })
  }

}
/*删除用户*/
const delete_user = (id)=>{
  if(confirm('确认删除吗？')){
    //restful风格
    axios.post(BASE_URL+'/v1/user/delete/'+id)
        .then((response)=>{
          if(response.data.code===2000){
            ElMessage.success('删除成功')
            load_user()
          }else{
            ElMessage.error(response.data.msg)
          }

        })
  }
}
const test1 =()=>{
  alert('1')
}
//页面加载完毕立即执行
onMounted(()=>{
  load_user();
})

const save_user_form_rules = ref({
    username:[
        {required:true,message:'用户名不能为空',trigger:'blur'},
        {pattern:/^([a-zA-Z0-9_]|[\u4e00-\u9fa5]){2,20}$/,message:'用户名必须是3-20位的字母、数字、下划线、中文',trigger:'blur'}
    ],
    email:[
        {required:true,message:'邮箱不能为空',trigger:'blur'},
        {pattern:/^[a-zA-Z0-9_]+@[A-Za-z0-9]+(\.[a-zA-Z]+)+$/,message:'邮箱格式不正确',trigger:'blur'}
    ],
    level:[
        {required:true,message:'职级不能为空'}
    ],
    parentId:[
        {required:true,message:'上级领导不能为空'}
    ],
    phone:[
        {required:true,message:'手机号不能为空',trigger:'blur'},
        {pattern:/^1[3456789]\d{9}$/,message:'手机号格式不正确',trigger:'blur'}
    ],
    age:[
        {required:true,message:'年龄不能为空',trigger:'blur'},
        {pattern:/^\d*$/,message:'年龄必须是数字',trigger: 'blur'}
    ],
    gender:[
        {required:true,message:'请选择性别'}
    ],
    status:[{required:true,message:'请选择状态'}]


})


</script>

<style scoped>

</style>